package com.dsideal.cloud.cas.client.utils;

import com.alibaba.fastjson.JSONObject;
import com.dsideal.cloud.auth.common.util.jwt.IJWTInfo;
import com.dsideal.cloud.cache.service.RedisService;
import com.dsideal.cloud.cas.client.config.MysqlConfig;
import com.dsideal.cloud.cas.client.properties.KeyConfiguration;
import com.dsideal.cloud.common.constant.ErrorCode;
import com.dsideal.cloud.common.exception.BaseException;
import com.dsideal.cloud.common.log.DsLogger;
import com.dsideal.cloud.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author suny
 */
@Component
public class JwtTokenUtil {

    private final static DsLogger log = DsLogger.buildLogger(JwtTokenUtil.class);

    /**
     * 作废
     */
    @Deprecated
    @Value("${jwt.expire}")
    private int expire;
    @Deprecated
    @Value("${jwt.pcExpire:604800}")
    private int pcExpire;


    public final String mobile = "mobile";
    public final String web="web";
    public final String pc = "pc";

    /**
     * redis key
     * 登录 ua 信息
     */
    private final String commonLoginWay = "common.login.way";

    /**
     * 数据库 key 字段
     */
    private final String configValue = "config_value";

    /**
     * 全局配置缓存前缀
     */
    String GLOBAL_CONFIG = "base_global_config:";


    @Value("${auth.user.token-header}")
    private String tokenHeader;

    @Autowired
    private KeyConfiguration keyConfiguration;

    @Autowired
    private RedisService redisService;

    @Autowired
    private MysqlConfig mysqlConfig;


    /**
     * 生成token
     * @param jwtInfoForCas jwtInfoForCas
     * @return token
     * @throws Exception
     */
    public String generateToken(JWTInfoForCas jwtInfoForCas) {
        String token = "";
        try {
            token = JWTHelperForCas.generateToken(jwtInfoForCas, keyConfiguration.getUserPriKey(), getExpireByUa(jwtInfoForCas.getUa()));
        } catch (Exception e) {
            log.error("generateToken error {}", e);
        }
        return token;
    }

    /**
     * token 获取信息
     * @param token
     * @return 用户信息
     * @throws Exception
     */
    public IJWTInfo getInfoFromToken(String token) throws Exception {
        return JWTHelperForCas.getInfoFromToken(token, keyConfiguration.getUserPubKey());
    }


    /**
     * 根据ua信息，查询过期时间
     * @param ua 信息
     * @return 过期时间
     */
    public int getExpireByUa(String ua) {
        int expire = 0;
        String uaInfo = redisService.get(GLOBAL_CONFIG + commonLoginWay);
        if(StringUtils.isBlank(uaInfo)){
            Map<String, Object> map = mysqlConfig.queryCommonLoginWay();
            if(map != null){
                uaInfo = String.valueOf(map.get(configValue));

            }
        }

        JSONObject jsonObject = JSONObject.parseObject(uaInfo);

        try {
            expire = Integer.parseInt(jsonObject.getString(ua)) * 24 * 60 * 60;
        } catch (NumberFormatException e) {
            throw new BaseException(ErrorCode.USER_UA_FAIL);
        }
        return expire;
    }
}
